from django_redis import get_redis_connection
from redis import RedisError
from rest_framework import serializers
import logging


from utils.constants import SMS_CODE_EXPRIE
logger = logging.getLogger('meiduo')


class VerificationSmsCodeSerializer(serializers.Serializer):
    """
    校验的是:短信验证码
    """
    text = serializers.CharField(max_length=4, min_length=4, required=True, label="用户输入的图片验证码")
    image_code_id = serializers.UUIDField(label="uuid", required=True)

    def validate(self, attrs):
        text = attrs.get("text")
        image_code_id = attrs.get("image_code_id")

        redis_conn = get_redis_connection("code")
        redis_text = redis_conn.get("img_%s" %image_code_id)

        # 校验是否过期
        if redis_text is None:
            return serializers.ValidationError("图片验证码已经过期了")

        # 删除
        try:
            redis_conn.delete("img_%s" %image_code_id)
        except RedisError as e:
            logger.error(e)

        # 对比
        if text.lower() != redis_text.decode().lower():
            return serializers.ValidationError("验证码错误")

        return attrs





